import React, { Component } from 'react'
import uuid from '../../server/UUIDUtils'
import { Button, WingBlank, Checkbox, List, WhiteSpace, Toast, TextareaItem } from 'antd-mobile'
import getData from '../../server/GetData'
import { getSearchParams } from '../../utils/param'

import './index.css'

const CheckboxItem = Checkbox.CheckboxItem;
let itemIndex; // 用于定位没有被填写的问题，并滚屏定位
export default class Questionnaire extends Component {
    constructor(props){
        super(props)
        this.state = {
            wenjuan: {},
            questList: [],
            checkedIndexList: [], // 用于标记哪些问题被勾选
            done: false,
        }
    }
    componentDidMount(){
        document.title = '满意度调查'
        let searchParams = getSearchParams(this.props.location.search)
        let name = decodeURIComponent(searchParams.name)
        let hosArea = decodeURIComponent(searchParams.bedNo)
        let phone = searchParams.phone
        let departmentName = decodeURIComponent(searchParams.depName)
        let departmentId = searchParams.depId
        let deptType = searchParams.deptType
        let wjId = searchParams.wjId
        Toast.loading('问卷加载中...', 30, () => {});
        getData({
            data: {
              bizContent: {},
              method: 'getMydQuestion',
              bizId: uuid()
            }
          }).then(res => {
            Toast.hide()
              if(res.rspCode != 200){
                Toast.info(res.rspMsg, 2);
              } else if(res.bizRspCode != 1){
                Toast.info(res.bizRpsMsg, 2);
              } else {
                let bizContent = res.bizContent
                let wenjuanList = JSON.parse(bizContent).wenjuanList
                console.log(wenjuanList)
                let wenjuan
                if(wenjuanList.length){
                    wenjuanList.forEach(wj => {
                        if(wj.wjId === wjId){
                            wenjuan = wj
                        }
                    })
                }
                if(!wenjuan){
                    Toast.info('没找到对应问卷', 2);
                    return
                }
                let questList = wenjuan.questList
                // 根据索引来给questIndex赋值，避免后台可能出现的questIndex缺失问题
                questList.forEach((item, i) => {
                  item.questIndex = i + 1
                })
                // 根据问卷问题长度处理用来做标记的数组checkedIndexList
                let checkedIndexList = [];
                for(let i = 0; i <  questList.length; i++){
                    if(questList[i].questType === '01'){ // 单选预设null
                        checkedIndexList.push(null) 
                    } else if(questList[i].questType === '02'){ // 多选预设一个空数组
                        checkedIndexList.push([])
                    } else if(questList[i].questType === '03'){ // 输入预设空字符串
                        checkedIndexList.push('')
                    } 
                }
                
                this.setState({
                    wenjuan,
                    questList,
                    done: true,
                    checkedIndexList
                })
              }
          }).catch(err => {
            Toast.hide()
          })
    }

    /**
     * 单选逻辑
     * @param {Number} questIndex 问题索引 (从1开始)
     * @param {Number} optionIndex 选项索引 (从0开始)
     */ 
    onRadioChange(questIndex, optionIndex){
        questIndex = questIndex/1
        optionIndex = optionIndex/1

        // 深拷贝checkedIndexList
        let arr = this.state.checkedIndexList.concat([])
        arr[questIndex - 1] = optionIndex
        this.setState({
            checkedIndexList: arr
        })
    }

    /**
     * 多选逻辑
     * @param {Number} questIndex 问题索引 (从1开始)
     * @param {Number} optionIndex 选项索引 (从0开始)
     */ 
    onCheckBoxChange(questIndex, optionIndex){
        questIndex = questIndex/1
        optionIndex = optionIndex/1
        // 深拷贝checkedIndexList
        let arr = this.state.checkedIndexList.concat([])
        let checkArr = arr[questIndex - 1]
        let index = checkArr.indexOf(optionIndex)
        if(index === -1){
            checkArr.push(optionIndex)
        } else {
            checkArr.splice(index, 1)
        }

        this.setState({
            checkedIndexList: arr
        })
    }

    /**
     * 输入逻辑
     * @param {Number} questIndex 问题索引 (从1开始)
     * @param {String} str 输入内容
     */ 
    onBlur(questIndex, str){
        questIndex = questIndex/1

        // 深拷贝checkedIndexList
        let arr = this.state.checkedIndexList.concat([])
        arr[questIndex - 1] = str
        this.setState({
            checkedIndexList: arr
        })
    }

    /**
     * 提交问卷
     */ 
    onSubmit(){
      if(!this.Validator()){
            this.scrollTo()
            Toast.info('请填写完整问卷内容', 2);
        } else {
            let params = this.getParams()
            this.saveMyAnswer(params)
        }
    }
    scrollTo(){
        let dom = document.querySelector('.item'+(itemIndex+1))
        window.scrollTo(0, dom.offsetTop)
    }

    /**
     * 生成提交问卷所需参数
     */ 
    getParams(){
        let wenjuan = this.state.wenjuan
        let questList = this.state.questList
        let params = {
            wjId: wenjuan.wjId,
            questList: []
        }
        this.state.checkedIndexList.forEach((item, index) => {
            // 基本入参字段
            let param = {
                quest: questList[index].quest,
                questId: questList[index].questId,
                questIndex: questList[index].questIndex,
                questType: questList[index].questType,
            }

            // 单选入参
            if(typeof item === 'number'){
                let option = {}
                questList[index].itemList.forEach(item2 => {
                    if(item2.optionIndex == item){
                        option = item2
                    }
                })
                param.itemList = [option]
            } 
            // 多选入参 
            else if(typeof item === 'object' && item !== null){
                param.itemList = []
                item.forEach(i => {
                    questList[index].itemList.forEach(item2 => {
                        if(item2.optionIndex == i){
                            param.itemList.push(item2)
                        }
                    }) 
                })
            } 
            // 输入入参
            else if(typeof item === 'string'){
                param.inputValue = item
            }
            params.questList.push(param)
        })
        return params
    }

    /**
     * 提交答案
     */ 
    saveMyAnswer(params){
        let that = this
        Toast.loading('问卷提交中...', 30, () => {});
        let searchParams = getSearchParams(this.props.location.search)
        params.name = decodeURIComponent(searchParams.name)
        params.phone = searchParams.phone
        params.departmentName = decodeURIComponent(searchParams.depName)
        params.departmentId = searchParams.depId
        if(searchParams.deptType === 'zy'){
            params.inhosTime = searchParams.inhosTime
            params.patientRelation = decodeURIComponent(searchParams.patientRelation)
        }
        getData({
            data: {
              bizContent: params,
              method: 'saveMydAnswer',
              bizId: uuid()
            }
        }).then(res => {
            if(res.rspCode != 200){
                Toast.info(res.rspMsg, 2);
            } else if(res.bizRspCode != 1){
                Toast.info(res.bizRpsMsg, 2);
            } else {
                Toast.info('问卷提交成功！', 2, function(){
                    that.props.history.replace({
                        pathname: '/result',
                        search: `?resultMsg=${encodeURIComponent('问卷提交成功!')}`
                    })
                })
            }
        }).catch(err => {
            Toast.info(err)
        })
    }

    /**
     * 提交检验
     */ 
    Validator(){
        let flag = true;
        let list = this.state.checkedIndexList
        for(let i = 0; i < list.length; i++){
            if(list[i] === null){
                flag = false;
                itemIndex = i
                break;
            } else if((list[i] instanceof Array)&&list[i].length === 0){
                flag = false;
                itemIndex = i
                break;
            }
        }
        return flag
    }

    /**
     * 根据问卷类型渲染单选、多选、填写样式
     * @param {Object} item 问题对象
     */ 
    renderOptions(item){
        // 单选
        if(item.questType === '01'){
            return (
                <div>
                    {item.itemList.map(i => (
                      <CheckboxItem
                      key={item.questIndex*1000 + i.optionIndex/1} 
                      onChange={() => this.onRadioChange(item.questIndex, i.optionIndex)} 
                      checked={this.state.checkedIndexList[item.questIndex - 1] === i.optionIndex/1}
                      >
                        {i.optionValue}
                      </CheckboxItem>
                    ))}
                </div>
            )
        } 
        // 多选
        else if(item.questType === '02'){
            return (
                <div>
                    {item.itemList.map(i => (
                      <CheckboxItem 
                      className="check-item"
                      key={item.questIndex*1000 + i.optionIndex/1} 
                      onChange={() => this.onCheckBoxChange(item.questIndex, i.optionIndex)} 
                      >
                        {i.optionValue}
                      </CheckboxItem>
                    ))}
                </div>
            )
        } 
        // 输入
        else if(item.questType === '03'){
            return (
                <TextareaItem
                onBlur={(str) => this.onBlur(item.questIndex, str)}
                rows={5}
                count={100}
              />
            )
        }
    }

    renderValidateList(){
        return (
            <div className="questionnaire-class">
                <WingBlank>
                    {this.state.questList.map(item => (
                        <div className={'item'+item.questIndex}>
                            <List renderHeader={item.questIndex + '. ' + item.quest}>
                                {/* 根据不同问卷类型来渲染对应内容 */}
                                { this.renderOptions(item) }
                            </List>
                            <WhiteSpace/>
                        </div>
                    ))}
                    <WhiteSpace size="lg"/>
                    <Button onClick={e => {this.onSubmit()}} className="btn-next">提交</Button>
                    <WhiteSpace size="lg"/>
                </WingBlank>
            </div>
        )
    }
    renderNotValidateList(){
        return <div></div>
    }
    render() {
        if(this.state.done){
            return this.renderValidateList()
        } else {
            return this.renderNotValidateList()
        }
    }
}
